# -*- encoding=utf8 -*-
__author__ = "chen"
from datetime import datetime
from common.common_util import *
def cangbaotu(hwnd):
    try:
        connect_device(f"Windows:///{hwnd}")
        pcos = wait(Template(r"cangbaotu_home.png", record_pos=(0.358, 0.153), resolution=(1600, 900)), 5)
        x = random.randint(-20, 20)
        y = random.randint(-1, 11)
        sleep(2)
        touch((pcos[0] + x, pcos[1] + y))
        return True
    except:
        print("xxxxxxxxxxxxx")
        return False
def get_hwnds(id):
    '''
    根据窗口标题获取对应句柄值
    :param id: 含有某个字段
    :return:
    '''
    hwnds = get_all_windows("梦幻西游")
    for i in range(len(hwnds)):
        title = win32gui.GetWindowText(hwnds[i])
        if f"[{id}]" in title:
            hwnd = hwnds[i]
            return hwnd
def creat_json_data(device_titles):
    '''
    根据设备数量，创建存放记录数据
    :param device_titles:
    :return:
    '''
    json_data = []
    for i in range(len(device_titles)):
        data = {"dev":device_titles[i],
                "hwnd":get_hwnds(device_titles[i]),
                "stop_falge": False,
                "start_time":datetime.now()
                }
        json_data.append(data)
    return json_data
def quit_condit(json_data,condit):
    #判断结束程序条件,期望值与实际值相等，就结束执行
    ql = True
    for i in range(len(json_data)):
        fl = json_data[i][condit] == False
        ql = ql & fl
    return ql
def run_mask_new(device_titles):
    #minimize_pycham()  # 最小化pycharm
    if len(device_titles)==0:
        hwnds = get_all_windows("梦幻西游")
        json_data = []
        for i in range(len(hwnds)):
            data = {"dev":win32gui.GetWindowText(hwnds[i]),
                    "hwnd":hwnds[i],
                    "start_time": datetime.now(),
                    "falge":True
                    }
            json_data.append(data)
    else:
        json_data = creat_json_data(device_titles)
    for i in range(100):
        for j in range(len(json_data)):
            if json_data[j]["falge"]:
                hp = cangbaotu(json_data[j]["hwnd"])
                print(f"窗口信息：{hp}")
            #   当前存在藏宝图
                if hp:
                    json_data[j]["start_time"] = datetime.now()
                else:
                #  对时间差值进行判断
                #     baoguo = exists(Template(r"tpl1725454215071.png", record_pos=(0.466, 0.261), resolution=(494, 398)))
                    shichang = datetime.now() - json_data[j]["start_time"]
                    if shichang.seconds > 600:
                        json_data[j]["stop_falge"] =False
            print(json_data)

        #结束判断
        if quit_condit(json_data, "falge"):
            break

if __name__ == '__main__':
    # 为空时，全部执行
    device_titles = []
    run_mask_new(device_titles)




